﻿//+-------------------------------------------------------------------------------------------------------------------------------------------------------
//
//Description: Interaction logic for OpenFileWindow.xaml
//Author: Aravind Ramarathinam (aravr@microsoft.com)
//
//Copyright © Microsoft Corporation
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
//INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
// 
//--------------------------------------------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using VmroleAuthor.Helpers;
using VmroleAuthor.ViewModels;

namespace VmroleAuthor.Views
{
    /// <summary>
    /// Interaction logic for OpenFileWindow.xaml
    /// </summary>
    public partial class OpenFileWindow : UserControl
    {
        public const string OpenFileWindowName = "OpenFileWindow";

        public static DependencyProperty FileLocationProperty = DependencyProperty.Register("FileLocation", typeof(string), typeof(OpenFileWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static DependencyProperty WorkingDirProperty = DependencyProperty.Register("WorkingDir", typeof(string), typeof(OpenFileWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


        public bool DataValid { get; private set; }        

        public CloudServiceManagerFileType CloudServiceManagerFileType { get; private set; }

        public ResourceExtensionStorageInfo ResourceExtensionStorageInfo { get; private set; }

        public ResourceDefinitionStorageInfo ResourceDefinitionStorageInfo { get; private set; }

        public OpenFileWindow()
        {
            InitializeComponent();
        }

        public static string GetWorkingDirectoryName(string fileName)
        {
            string workingDir = null;
            string dirName = System.IO.Path.GetDirectoryName(fileName);
            if (!string.IsNullOrEmpty(dirName))
            {
                string newFolderName = System.IO.Path.GetFileNameWithoutExtension(fileName);
                if (string.IsNullOrEmpty(newFolderName))
                {
                    newFolderName = "GeneratedFolder";
                }
                Random rand = new Random(fileName.GetHashCode());
                string suffix = DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss-fff").ToString(CultureInfo.InvariantCulture);
                string updatedFolderName = string.Concat(newFolderName, "-", suffix, "-", rand.Next(100));          
                workingDir = System.IO.Path.Combine(dirName, updatedFolderName);
            }
            return workingDir;
        }

        private void BrowseFile(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
                {
                    DefaultExt = ".resextpkg",
                    Filter = "Resource Extension Or Resource Definition Package (*.resextpkg;*.resdefpkg)|*.resextpkg;*.resdefpkg|Resource Definition (*.resdef)|*.resdef|All Files (*.*)|*.*"
                };

            dlg.Title = "Open Resource Extension Package or Resource Definition Package or Resource Definition";           
            bool? result = dlg.ShowDialog();
            // Process open file dialog box results 
            if (result == true)
            {               
                if (dlg.FileName != null)
                {
                    FileLocation.Text = dlg.FileName;
                    BindingExpression be = GetBindingExpression(FileLocationProperty);
                    if (be != null)
                    {
                        be.UpdateSource();
                    }
                    WorkingDir.Text = GetWorkingDirectoryName(dlg.FileName);
                   
                    BindingExpression be2 = GetBindingExpression(WorkingDirProperty);
                    if (be2 != null)
                    {
                        be2.UpdateSource();
                    }
                }               
            }
        }
       

        public void OkButton_Click(object sender, RoutedEventArgs e)
        {
            if (!System.IO.File.Exists(FileLocation.Text))
            {
                MessageBox.Show("Selected File does not exist: " + FileLocation.Text, DefinitionViewModel.ToolHeader);
            }           
            else
            {
                try
                {
                    if (PackagingFormatHelper.IsPackage(FileLocation.Text))
                    {
                        this.CloudServiceManagerFileType = PackagingFormatHelper.GetFileType(FileLocation.Text);
                        PackagingFormatHelper.ExtractPackage(FileLocation.Text, WorkingDir.Text, this.CloudServiceManagerFileType);                        
                        if (this.CloudServiceManagerFileType == CloudServiceManagerFileType.ResourceExtensionPackage)
                        {
                            string jsonFileNameInsidePackage;
                            PackagingFormatHelper.GetResextPkgDetails(WorkingDir.Text, out jsonFileNameInsidePackage);
                            this.ResourceExtensionStorageInfo = new ResourceExtensionStorageInfo
                                {
                                    FileToSavePath = FileLocation.Text,
                                    JsonFileName = jsonFileNameInsidePackage,
                                    WorkingDir = WorkingDir.Text
                                };
                            this.DataValid = true;
                        }
                        else if (this.CloudServiceManagerFileType == CloudServiceManagerFileType.ResourceDefinitionPackage)
                        {
                            string resdefJsonFile;
                            string viewdefJsonFile;
                            string smallIconFile, mediumIconFile, largeIconFile;                            
                            List<string> resourceFileNames;
                            PackagingFormatHelper.GetResdefPkgDetails(WorkingDir.Text, out resdefJsonFile, out viewdefJsonFile, out smallIconFile, out mediumIconFile, out largeIconFile, out resourceFileNames);
                            this.ResourceDefinitionStorageInfo = new ResourceDefinitionStorageInfo
                                {
                                    FileToSavePath = FileLocation.Text,
                                    JsonFileName = resdefJsonFile,
                                    ViewDefFileName = viewdefJsonFile,
                                    SmallIconFileName = smallIconFile,
                                    MediumIconFileName = mediumIconFile,
                                    LargeIconFileName = largeIconFile,
                                    ResourceFileNames = resourceFileNames,
                                    WorkingDir =  WorkingDir.Text,
                                    IsResdefPkg =  true
                                };
                            this.DataValid = true;
                        }                                                                                                                                     
                    }
                    else
                    {
                        this.CloudServiceManagerFileType = PackagingFormatHelper.GetFileType(FileLocation.Text);
                        if (this.CloudServiceManagerFileType == CloudServiceManagerFileType.ResourceDefinition)
                        {
                            this.ResourceDefinitionStorageInfo = new ResourceDefinitionStorageInfo
                            {
                                FileToSavePath = FileLocation.Text,
                                JsonFileName = FileLocation.Text,
                                WorkingDir = WorkingDir.Text,
                                IsResdefPkg = false
                            };
                            this.DataValid = true;
                        }
                        else
                        {
                            MessageBox.Show("This file format is not supported currently", DefinitionViewModel.ToolHeader);   
                        }                        
                    }
                    
                    if (this.DataValid)
                    {
                        Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == OpenFileWindowName);
                        if (win != null) win.Close(); 
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Malformed package. Error while extracting the package.: " + ex.Message, DefinitionViewModel.ToolHeader);                  
                }                                       
            }           
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DataValid = false;
            Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == OpenFileWindowName);
            if (win != null) win.Close();           
        }
    }
}
